﻿#-------------------------------------------------------------------------------
# Name:        module1
# Purpose:
#
# Author:      Particulier
#
# Created:     19/03/2011
# Copyright:   (c) Particulier 2011
# Licence:     <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python
import PyQt4.QtGui
import PyQt4.Qwt5 as Qwt
from guiqwt.plot import CurveDialog
from guiqwt.builder import make
from PyQt4 import QtGui, QtCore
from MainForm import Ui_MainWindow
import sys
from  AdwinPro import AIN_F8_14_revb3
from scipy import linspace,arange,fft
from guiqwt.tools import HRangeTool
from guiqwt.builder import make
import numpy as np
from datetime import date
import  os
import string

#---------------------------------------------------

class SAA8(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)

        # Configure l'interface utilisateur.
        self.setupUi(self)

        self.bootloader="ADwin10.btl"  # boot loader du T10
        self.sp=20         # periode du process dans le T10
        self.nbchannel=1    # nombre de voie acquisition
        self.srate=2000000 # frequence echantillonnage
        self.mode=1         # mode acquisition
        self.max_buffer_size=1048575 # max echantillon par voie
        self.process_name ="acq_1.TA1"  # nom du process
        self.processNumber= 1  # on utilise le process 1
        self.nbpoint = 8192 # nb. point acquisition par voie
        self.level = 0 # initialise le gain +/- 10 V
        self.tab_level=["+/- 10V","+/- 5V","+/- 2.5V","+/- 1.25V"]
        self.slope=2  # trigger sur front descendant
        self.tab_slope=["rising edge","falling edge"]
        self.average=1  # moyenne
        self.delay = 0 # retard acquisition
        self.nbpfft= 2048 # nb. point FFT
        self.rightfrequency= 1000000 # frequence de droite pour affichage
        self.projectName= str("data")  # nom du projet
        self.fileName= str("temp")   # nom des fichiers
        self.flagConnected= False  # flag de connection ethernet
        self.flagProcessLoaded= False # flag chargement du process
        self.flagOneInstanceSignal=0 #pour affichage , initialisation puis update
        self.flagOneInstanceFFT=0 #pour affichage FFT, initialisation puis update
        for i in range(8):
            mess="self.curve"+str(i)+"=None"
            exec(mess)
            mess="self.curvefft"+str(i)+"=None"
            exec(mess)
        self.win_signal=None   # initialise fenetre signal
        self.win_fft=None      # initialise fentre FFT
        self.win_fft_exist = False
        self.win_signal_exist = False
        self.path=""
        self.filecounter=0  # initialise le compteur de fichier
        self.header=np.zeros(16,dtype='float')  # header

        # Connecte le bouton.
        #self.connect(self.pushButton, QtCore.SIGNAL("clicked()"),message)
        # menus
        self.connect(self.actionClass_parameters,QtCore.SIGNAL("triggered()"),classParameters)
        self.connect(self.actionConnect,QtCore.SIGNAL("triggered()"),OnConnect_Ethernet)
        self.connect(self.actionDisconnect,QtCore.SIGNAL("triggered()"),OnDisConnect_Ethernet)
        self.connect(self.actionQuit,QtCore.SIGNAL("triggered()"),App_Quit)


        #combobox
        self.connect(self.comboBoxAcqChannel, QtCore.SIGNAL("currentIndexChanged(int)"), OnChange_Channel)
        self.connect(self.comboBoxLevel, QtCore.SIGNAL("currentIndexChanged(int)"), OnChange_Level)
        self.connect(self.comboBoxTrigger, QtCore.SIGNAL("currentIndexChanged(int)"), OnChange_Trigger)

        #editbox
        self.connect(self.lineEditSampleRate, QtCore.SIGNAL("returnPressed()"), OnChange_srate)
        self.connect(self.lineEditPointNumber, QtCore.SIGNAL("returnPressed()"), OnChange_PointNumber)
        self.connect(self.lineEditAverage, QtCore.SIGNAL("returnPressed()"), OnChange_Average)
        self.connect(self.lineEditDelay, QtCore.SIGNAL("returnPressed()"), OnChange_Delay)
        self.connect(self.lineEditNbPointFFT, QtCore.SIGNAL("returnPressed()"), OnChange_fftPoint)
        self.connect(self.lineEditRightFrequency, QtCore.SIGNAL("returnPressed()"), OnChange_RightFrequency)
        self.connect(self.lineEditProjectname, QtCore.SIGNAL("returnPressed()"), OnChange_ProjectName)
        self.connect(self.lineEditFileName, QtCore.SIGNAL("returnPressed()"), OnChange_FileName)


        # Pushbouton
        self.connect(self.pushButtonBootLoader,QtCore.SIGNAL("clicked()"),OnClick_BootLoader)
        self.connect(self.pushButtonLoadProcess,QtCore.SIGNAL("clicked()"),OnClick_LoadProcess)
        self.connect(self.pushButtonInitProcess,QtCore.SIGNAL("clicked()"),OnClick_InitProcess)
        self.connect(self.pushButtonStartProcess,QtCore.SIGNAL("clicked()"),OnClick_StartProcess)
        self.connect(self.pushButtonStopProcess,QtCore.SIGNAL("clicked()"),OnClick_StopProcess)
        self.connect(self.pushButtonClearProcess,QtCore.SIGNAL("clicked()"),OnClick_ClearProcess)
        self.connect(self.pushButtonSingleAcq,QtCore.SIGNAL("clicked()"),OnClick_SingleAcq)
        self.connect(self.pushButtonAcqAverage,QtCore.SIGNAL("clicked()"),OnClick_AverageAcq)
        self.connect(self.pushButtonBoot,QtCore.SIGNAL("clicked()"),OnClick_Boot)
        self.connect(self.pushButtonRazCpt,QtCore.SIGNAL("clicked()"),OnClick_RazCounter)




        # initialise les menus et onglets
        self.actionDisconnect.setEnabled(False)
        # initialise les boutons
        self.pushButtonBootLoader.setEnabled(False) # tous deconnecte
        self.pushButtonLoadProcess.setEnabled(False)
        self.pushButtonInitProcess.setEnabled(False)
        self.pushButtonStartProcess.setEnabled(False)
        self.pushButtonStopProcess.setEnabled(False)
        self.pushButtonClearProcess.setEnabled(False)
        self.pushButtonBoot.setEnabled(False)

    def xplot_data(self,buf,nbvoie,nbpoint,fs):
        " affiche les voies acquisition"
        t=[]    # initiale temps
        dt=1.0/fs   # periode des signaux
        t=linspace(0,(nbpoint-1)*dt,nbpoint) # axe des temps
        if w.flagOneInstanceSignal==0:   # premier passage initialise fenetre
            w.win_signal = CurveDialog(edit=False, toolbar=True, wintitle="Temporal signal",
                          options=dict(title="Signal", xlabel="Temps",
                                       ylabel="Amplitude"))
            w.win_signal.add_tool(HRangeTool)   # barre outils selection zone
            p1 = w.win_signal.get_plot()        # initialise le plot
            for i in range(nbvoie):
                y=buf[i][0:nbpoint] # recup voie
                mess="w.curve"+str(i)+"=make.curve(t, y, color=\"b\",title=\"voie "+str(i)+"\")" # intitialise la courne
                exec(mess)
                mess="p1.add_item(w.curve"+str(i)+")"  # ajoute la courbe au plot
                exec(mess)
            w.win_signal.get_itemlist_panel().show()
            #p1.set_items_readonly(False)
            w.flagOneInstanceSignal=1       # flip flop
        if w.flagOneInstanceSignal==1:      # second passage
            for i in range(nbvoie):
                y=buf[i][0:nbpoint]         # recup voies
                mess="w.curve"+str(i)+".set_data(t, y)" # on met a jour uniquement les donnees
                exec(mess)
                mess="w.curve"+str(i)+".plot().replot()" # et on re plot
                exec(mess)
        w.win_signal.show()   # affiche figure
        w.win_signal_exist = True
        return

    def xplot_fft(self,buf,nbvoie,nbpoint,fs,npfft,fr):
        "fft les voies acquisition"
        " buf : buffer des voies acquisition"
        "nbvoie : nb. de voie acquisition"
        "nbpoint : taille de la voie en point"
        "fs : frequence echantillonnage"
        "npfft : nb. point de la fft"
        "fr : frequence de visualisation a droite <Fs/2"
        f=[]        # initialise frequence
        sfft=[]     # initialise FFT
        m=[]        # initailise le module
        df=float(fs/npfft)       # pas fft
        f=arange(0,fs,df)     # axe des freq
        index=int(npfft*fr/fs) # index  axe frequence doite (visu)
        if w.flagOneInstanceFFT==0:
            w.win_fft = CurveDialog(edit=False, toolbar=True, wintitle="FFT signal",
                          options=dict(title="FFT signal", xlabel="Freq [Hz]",
                                       ylabel="Amplitude"))
            w.win_fft.add_tool(HRangeTool)   # barre outils selection zone
            p1 = w.win_fft.get_plot()        # initialise le plot
            for i in range(nbvoie):
                y=buf[i][0:nbpoint]     # signaux
                sfft=fft(y,npfft)       # FFT complexe
                m=abs(sfft)/npfft       # module et normalisation
                m[0]=0                  # enleve dc
                mess="w.curvefft"+str(i)+"=make.curve(f[0:index],m[0:index], color=\"r\",title=\"voie "+str(i)+"\")" # intitialise la courne
                exec(mess)
                mess="p1.add_item(w.curvefft"+str(i)+")"  # ajoute la courbe au plot
                exec(mess)
            w.win_fft.get_itemlist_panel().show()
            #p1.set_items_readonly(False)
            w.flagOneInstanceFFT=1
        if w.flagOneInstanceFFT==1:
            for i in range(nbvoie):
                y=buf[i][0:nbpoint]     # signaux
                sfft=fft(y,npfft)       # FFT complexe
                m=abs(sfft)/npfft       # module et normalisation
                m[0]=0                  # enleve dc
                mess="w.curvefft"+str(i)+".set_data(f[0:index],m[0:index])" # on met a jour uniquement les donnees
                exec(mess)
                mess="w.curvefft"+str(i)+".plot().replot()" # et on re plot
                exec(mess)
        w.win_fft.show()   # affiche figure
        w.win_fft_exist = True
        return


def App_Quit():
#    sys.exit(app.exec_())
    w.close()

def  classParameters():
    "affiche les parametres de la classe"
    w.listinfo.addItem("-----")
    w.listinfo.addItem("Project name : "+w.projectName)
    w.listinfo.addItem("Filename name : "+w.fileName)
    w.listinfo.addItem("Sampling rate : "+str(w.srate)+"Hz")
    w.listinfo.addItem("T10 sampling period : "+str(w.sp)+" cycles")
    w.listinfo.addItem("Channel range : "+str(w.nbchannel))
    w.listinfo.addItem("Mode : "+str(w.mode))
    w.listinfo.addItem("Max. buffer size : "+str(w.max_buffer_size)+" samples")
    w.listinfo.addItem("Process name : "+w.process_name)
    w.listinfo.addItem("Number points acquisition by channel : "+ str(w.nbpoint))
    w.listinfo.addItem("Input level : "+w.tab_level[w.level])
    w.listinfo.addItem("trigger slope : "+w.tab_slope[w.slope-1])
    w.listinfo.addItem("Number of average : "+str(w.average))
    w.listinfo.addItem("Number of FFT point  : "+str(w.nbpfft))
    w.listinfo.addItem("Right frequency : "+str(w.rightfrequency)+" Hz")
    w.listinfo.scrollToBottom()


def OnChange_ProjectName():
    "modification du nom de projet"
    w.projectName = str(w.lineEditProjectname.text()).rstrip()
    w.listinfo.addItem("Project name : "+w.projectName)
    w.listinfo.scrollToBottom()


def OnChange_FileName():
    "modification du nom des fichiers"
#    w.fileName = w.lineEditFileName.text().remove(" ");
    w.fileName = str(w.lineEditFileName.text()).rstrip()
    w.listinfo.addItem("Filename name : "+w.fileName)
    w.listinfo.scrollToBottom()

def OnChange_Delay():
    "modifie les moyennes"
    w.delay=int(w.lineEditDelay.text()) # lecture editbox retard
    w.listinfo.addItem("retard acquisition en ms : "+str(w.delay))
    k.set_delay(w.delay)
    w.listinfo.scrollToBottom()
    
def OnChange_Average():
    "modifie le retard des voies"
    w.average=int(w.lineEditAverage.text()) # lecture editbox moyenne
    w.listinfo.addItem("Number of average : "+str(w.average))
    w.listinfo.scrollToBottom()
    

def OnChange_fftPoint():
    "modifie le nombre de point de la FFT"
    w.nbpfft = int(w.lineEditNbPointFFT.text())
    w.listinfo.addItem("Number of FFT point  : "+str(w.nbpfft))
    w.listinfo.scrollToBottom()


def OnChange_RightFrequency():
    "change la frequence affichage de droite"
    w.rightfrequency = int(w.lineEditRightFrequency.text())
    w.listinfo.addItem("Right frequency : "+str(w.rightfrequency)+" Hz")
    w.listinfo.scrollToBottom()


def OnChange_srate():
    "modifie la frequence echantillonnage"
    "et calcule la peiode pour le processeur T10"
    w.srate=int(w.lineEditSampleRate.text()) # lecture combobox
    w.sp=k.srate2sp(w.srate)   # calcul de la nouvelle periode
    w.listinfo.addItem("Sampling rate : "+str(w.srate)+"Hz")
    w.listinfo.addItem("T10 sampling period : "+str(w.sp)+" cycles")
    w.listinfo.scrollToBottom()
    if w.flagProcessLoaded:
        OnClick_InitProcess()

def OnChange_PointNumber():
    "modifie le nombre de point acquisition par voie"
    "doit etre inferieur au max echantillons par voie"
    w.nbpoint = int(w.lineEditPointNumber.text()) # lecture editbox
    w.listinfo.addItem("Number points acquisition by channel : "+ str(w.nbpoint))
    w.listinfo.scrollToBottom()
    if w.flagProcessLoaded:
        OnClick_InitProcess()
        OnClick_SingleAcq()

def  OnChange_Channel(nbchannel):
    "modification du nombre de voies acquisition"
    w.nbchannel=nbchannel+1  # change le nombre de voies acquisition
    w.listinfo.addItem("Channel range : "+str(w.nbchannel))
    w.mode,w.max_buffer_size,w.process_name=k.calcul_acq_mode(w.nbchannel)
    w.listinfo.addItem("Mode : "+str(w.mode))
    w.listinfo.addItem("Max. buffer size : "+str(w.max_buffer_size)+" samples")
    w.listinfo.addItem("Process name : "+w.process_name)
    w.labelMaxBufferSize.setText("Max. samples by channel : "+str(w.max_buffer_size))
    w.labelAcqMode.setText("Acq. mode : "+str(w.mode))
    w.listinfo.scrollToBottom()
    if w.win_fft_exist:
        w.win_fft.close()
        w.win_fft_exist = False
    if w.win_signal_exist:
        w.win_signal.close()
        w.win_signal_exist = False

    if w.flagProcessLoaded:
        w.flagOneInstanceFFT=0
        w.flagOneInstanceSignal=0
        OnClick_StopProcess()
        OnClick_LoadProcess()
        OnClick_InitProcess()
        OnClick_StartProcess()


def OnChange_Level(level):
    "mode  	    |	measurement range"
    "      0	|	+/- 10 V"
    "      1	|	+/- 5 V"
    "      2	|	+/- 2.5 V"
    "	     3	|	+/- 1.25 V"
    w.level=level  #  entre 0 et 3
    w.listinfo.addItem("Input level : "+w.tab_level[level])
    w.listinfo.scrollToBottom()
    if w.flagProcessLoaded:
        OnClick_InitProcess()

def OnChange_Trigger(slope):
    "modification du front de declanchement du trigger"
    w.slope=slope+1   # type du front
    w.listinfo.addItem("trigger slope : "+w.tab_slope[slope])
    w.listinfo.scrollToBottom()
    if w.flagProcessLoaded:
        OnClick_InitProcess()


def OnConnect_Ethernet():
    "connection du module Adwin ai PC via liaison socket"
    w.actionConnect.setEnabled(False)
    w.actionDisconnect.setEnabled(True)
    w.flagConnected= True
    w.listinfo.addItem("Ethernet connected")
    w.listinfo.scrollToBottom()
    #
    w.pushButtonBootLoader.setEnabled(True)
    w.pushButtonLoadProcess.setEnabled(False)
    w.pushButtonInitProcess.setEnabled(False)
    w.pushButtonStartProcess.setEnabled(False)
    w.pushButtonStopProcess.setEnabled(False)
    w.pushButtonClearProcess.setEnabled(False)
    w.pushButtonBoot.setEnabled(True)
    # creation dossier donnees
    racine=os.getcwd()  # garde la racine
    print racine
    today = date.today() # date du jour
    print today
    s=today.strftime("%Y%m%d") # conversion aaaammjj
    print w.projectName,len(w.projectName)
    w.path = os.path.join(racine,w.projectName,s)+os.sep
    print w.path
    if not os.path.exists(w.path):
        os.makedirs(w.path, mode=644)
        w.listinfo.addItem(w.path)
        w.listinfo.scrollToBottom()
    return

def OnDisConnect_Ethernet():
    "deconnexion du module par la liason ethernet"
    w.actionConnect.setEnabled(True)
    w.actionDisconnect.setEnabled(False)
    w.flagConnected= False
    w.listinfo.addItem("Ethernet disconnected")
    w.listinfo.scrollToBottom()
    #
    w.pushButtonBootLoader.setEnabled(False)
    w.pushButtonLoadProcess.setEnabled(False)
    w.pushButtonInitProcess.setEnabled(False)
    w.pushButtonStartProcess.setEnabled(False)
    w.pushButtonStopProcess.setEnabled(False)
    w.pushButtonClearProcess.setEnabled(False)
    w.pushButtonSingleAcq.setEnabled(False)
    w.pushButtonBoot.setEnabled(False)
    w.pushButtonAcqAverage.setEnabled(False)

def OnClick_Boot():
        OnClick_BootLoader()
        OnClick_LoadProcess()
        OnClick_InitProcess()
        OnClick_StartProcess()

def OnClick_RazCounter():
    "raz du compteur de fichier"
    w.filecounter=0

def OnClick_BootLoader():
    "chargement du bootloader"
    k.boot_loader(w.bootloader)    # charge le boot loader pour le T10
    w.listinfo.addItem("Boot loader loaded :" + w.bootloader)
    w.listinfo.scrollToBottom()
    #
    w.pushButtonBootLoader.setEnabled(True)
    w.pushButtonLoadProcess.setEnabled(True)
    w.pushButtonInitProcess.setEnabled(False)
    w.pushButtonStartProcess.setEnabled(False)
    w.pushButtonStopProcess.setEnabled(False)
    w.pushButtonClearProcess.setEnabled(False)

def OnClick_LoadProcess():
    "chargement du process"
    k.load_process(w.process_name)   # chargement du process
    w.flagProcessLoaded = True
    w.listinfo.addItem("Process loaded :" + w.process_name)
    w.listinfo.scrollToBottom()
    #
    w.pushButtonBootLoader.setEnabled(True)
    w.pushButtonLoadProcess.setEnabled(True)
    w.pushButtonInitProcess.setEnabled(True)
    w.pushButtonStartProcess.setEnabled(False)
    w.pushButtonStopProcess.setEnabled(False)
    w.pushButtonClearProcess.setEnabled(False)

def OnClick_InitProcess():
    "initialistion du process"
    k.set_gain(w.level)         # initialise les gains pour chaque voie
    k.set_buffersise(w.nbpoint)  # taille des buffers acquisition
    fs=w.srate           # frequence echantillonnage
    sp=k.srate2sp(fs)   # calcul de la periode pour le processeur
    k.set_sampling_period(sp) # initialise la preiode echantillonnage
    k.set_trigger(w.slope)          # trigger front descendant
    k.set_delay(w.delay)
    w.mode,w.max_buf_size,w.process_name=k.calcul_acq_mode(w.nbchannel)  # calcul du mode et taille max des buffers
    k.set_acq_mode(w.mode)      #initialisation du mode
    w.listinfo.addItem("Process initialised")
    w.listinfo.scrollToBottom()
    k.get_parameters()        # verif parametres envoyes PAR_(1..5)
    #
    w.pushButtonBootLoader.setEnabled(True)
    w.pushButtonLoadProcess.setEnabled(True)
    w.pushButtonInitProcess.setEnabled(True)
    w.pushButtonStartProcess.setEnabled(True)
    w.pushButtonStopProcess.setEnabled(False)
    w.pushButtonClearProcess.setEnabled(False)



def OnClick_StartProcess():
    "lancement du process"
    k.start_process(w.processNumber)  # lancement du process
    w.listinfo.addItem("Process running :" + str(w.processNumber))
    w.listinfo.scrollToBottom()
    #
    w.pushButtonBootLoader.setEnabled(True)
    w.pushButtonLoadProcess.setEnabled(True)
    w.pushButtonInitProcess.setEnabled(True)
    w.pushButtonStartProcess.setEnabled(True)
    w.pushButtonStopProcess.setEnabled(True)
    w.pushButtonClearProcess.setEnabled(False)
    # recupere les donnees
    print w.nbchannel,w.nbpoint,w.level,w.srate

    buffer=k.get_data(w.nbchannel,w.nbpoint,w.level) # transfert des buffers
    w.xplot_data(buffer,w.nbchannel,w.nbpoint,w.srate)
    # affiche les buffers
    w.xplot_fft(buffer,w.nbchannel,w.nbpoint,w.srate,w.nbpfft,w.rightfrequency)    # affiche les buffers
##    k.save_binary_file('signal',buffer,w.nbchannel,w.nbpoint)
    w.pushButtonSingleAcq.setEnabled(True)
    w.pushButtonAcqAverage.setEnabled(True)


def OnClick_StopProcess():
    "arret du process 1"
    k.stop_process(w.processNumber) # arret du process
    w.listinfo.addItem("Process stopped :" + str(w.processNumber))
    w.listinfo.scrollToBottom()
    #
    w.pushButtonBootLoader.setEnabled(True)
    w.pushButtonLoadProcess.setEnabled(True)
    w.pushButtonInitProcess.setEnabled(True)
    w.pushButtonStartProcess.setEnabled(True)
    w.pushButtonStopProcess.setEnabled(True)
    w.pushButtonClearProcess.setEnabled(True)



def OnClick_ClearProcess():
    "efface le process"
    k.clear_process(w.processNumber)
    #
    w.pushButtonBootLoader.setEnabled(True)
    w.pushButtonLoadProcess.setEnabled(True)
    w.pushButtonInitProcess.setEnabled(False)
    w.pushButtonStartProcess.setEnabled(False)
    w.pushButtonStopProcess.setEnabled(False)
    w.pushButtonClearProcess.setEnabled(False)
    w.listinfo.addItem("Process cleared :" + str(w.processNumber))
    w.listinfo.scrollToBottom()

def OnClick_SingleAcq():
    "acquisition simple"
    k.start_process(w.processNumber)  # lancement du process
    # recupere les donnees
    buffer=k.get_data(w.nbchannel,w.nbpoint,w.level) # transfert des buffers
    w.xplot_data(buffer,w.nbchannel,w.nbpoint,w.srate)    # affiche les buffers
    w.xplot_fft(buffer,w.nbchannel,w.nbpoint,w.srate,w.nbpfft,w.rightfrequency)    # affiche les buffers
    # header
    w.header[0]=w.srate
    w.header[1]=w.nbchannel
    w.header[2]=w.nbpoint
    w.header[3]=0  # numero de voie pour le moment zero
    w.header[4]=w.level
    w.header[5]=w.slope
    w.header[6]=w.average
    w.header[7]=0  # pas de moyenne
    if w.checkBoxSave.isChecked():
        if w.checkBoxInc.isChecked():
            flaginc=True
            k.save_binary_file(w.fileName,w.path,buffer,w.header,w.nbchannel,w.nbpoint,w.filecounter,flaginc)
            w.filecounter = w.filecounter + 1
        else:
            flaginc=False
            k.save_binary_file(w.fileName,w.path,buffer,w.header,w.nbchannel,w.nbpoint,w.filecounter,flaginc)
    k.stop_process(w.processNumber) # arret du process


def OnClick_AverageAcq():
    "acquisition avec des moyennes"
    moy=np.zeros((w.nbchannel,w.nbpoint),dtype='float')
    for i in range(w.average):
        k.start_process(w.processNumber)  # lancement du process
        # recupere les donnees
        buffer=k.get_data(w.nbchannel,w.nbpoint,w.level) # transfert des buffers
    #    k.save_binary_file('signal',buffer,w.nbchannel,w.nbpoint)
        print buffer.dtype, buffer.shape
        moy = moy + buffer
        k.stop_process(w.processNumber) # arret du process
        w.listinfo.addItem("Acquisition number :" + "%06d" % i)
        w.listinfo.scrollToBottom()
    moy=moy/w.average
    w.xplot_data(moy,w.nbchannel,w.nbpoint,w.srate)    # affiche les buffers
    # header
    w.header[0]=w.srate
    w.header[1]=w.nbchannel
    w.header[2]=w.nbpoint
    w.header[3]=0  # numero de voie pour le moment zero
    w.header[4]=w.level
    w.header[5]=w.slope
    w.header[6]=w.average
    w.header[7]=1  # avec des moyennes
    if w.checkBoxSave.isChecked():
        if w.checkBoxInc.isChecked():
            flaginc=True
            k.save_binary_file(w.fileName,w.path,moy,w.header,w.nbchannel,w.nbpoint,w.filecounter,flaginc)
            w.filecounter = w.filecounter + 1
        else:
            flaginc=False
            k.save_binary_file(w.fileName,w.path,moy,w.header,w.nbchannel,w.nbpoint,w.filecounter,flaginc)
    k.stop_process(w.processNumber) # arret du process





if __name__ == "__main__":
    #app = QtGui.QApplication(sys.argv)
    from guidata import qapplication
    app=qapplication()
    #
    w = SAA8()
    k=AIN_F8_14_revb3()   # initialise la carte AIN-F8/14 rev B3
    #
    w.show()
    sys.exit(app.exec_())

